package cn.com.gridinfo.sooc.utils;

import android.app.NotificationManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.view.KeyEvent;
import android.webkit.URLUtil;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.jeremy.arad.Arad;
import com.jeremy.arad.utils.Log;
import com.jeremy.arad.utils.StringUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import cn.com.gridinfo.sooc.R;
import cn.com.gridinfo.sooc.SoocApplication;
import cn.com.gridinfo.sooc.common.Const;
import cn.com.gridinfo.sooc.common.LocalMark;
import cn.com.gridinfo.sooc.common.UrlConst;
import cn.com.gridinfo.sooc.utils.versionHttp.AsyncCallback;
import cn.com.gridinfo.sooc.utils.versionHttp.AsyncTaskUtil;
import cn.com.gridinfo.sooc.utils.versionHttp.JsonUtil;
import cn.com.gridinfo.sooc.utils.versionHttp.Post;


public class VersionUpdate {

    private Context context;
    private NotificationManager nm;
    private String versionName;
    private Post post;
    private ProgressDialog dialog;
    private String fileMD5;
    private String strURL;
    private String fileEx = "";
    private String fileNa = "";
    private String currentFilePath = "";
    private static final String TAG = "AutoUpdate";
    private SoocApplication app;
    private Thread mThread;
    //下载地址
    String download_url = null;
    //更新信息
    String update_info = null;
    //更新需要的 md5校验
    String md5 = null;
    boolean isAutoUpdate = true;//默认自动更新true,点击设置里更新软件属于手动更新 false

    /**
     * 构造方法
     *
     * @param context
     * @param isAutoUpdate 是手动点击更新,还是系统自动更新
     */
    public VersionUpdate(Context context, boolean isAutoUpdate) {
        super();
        this.context = context;
        app = (SoocApplication) context.getApplicationContext();
        nm = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);
        versionName = app.deviceInfo.getVersionName();
        this.isAutoUpdate = isAutoUpdate;
    }

    /**
     * 构造方法
     *
     * @param context
     */
    public VersionUpdate(Context context) {
        super();
        this.context = context;
        app = (SoocApplication) context.getApplicationContext();
        nm = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);
        versionName = app.deviceInfo.getVersionName();

    }

    // 通知栏进度条
//    private Notification mNotification;

    //    private void notificationInit() {
//        // 通知栏内显示下载进度条
//        mNotification = new Notification();
//        mNotification.icon = R.drawable.ic_launcher;
//        mNotification.tickerText = "正在下载...";
//        mNotification.contentView = new RemoteViews(context.getPackageName(),
//                R.layout.notification_progress_bar);// 通知栏中进度布局
//        nm.notify(0, mNotification);
//    }
    private void startThread(Runnable run) {
        if (mThread != null)
            mThread.interrupt();
        mThread = new Thread(run);
        mThread.start();
    }

    //下载进度条
    public void showWaitDialog() {
        dialog = new ProgressDialog(context);
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        dialog.setTitle("下载更新");
        dialog.setIndeterminate(false);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setCancelable(false);

        dialog.show();
        dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                //强制更新时，按键退出应用
                if(app.updateMust==1) {
                    if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                        dialog.dismiss();
                        System.exit(0);
                        return true;
                    }
                }
                return false;
            }
        });

//        new MaterialDialog.Builder( context)
//                .title("下载更新")
//                .content("正在下载...")
//                .cancelable(false)
//                .contentGravity(GravityEnum.CENTER)
//                .progress(false, 100, true).progressIndeterminateStyle(true)
//                .cancelListener(new DialogInterface.OnCancelListener() {
//                    @Override
//                    public void onCancel(DialogInterface dialog) {
//                        if (mThread != null)
//                            mThread.interrupt();
//                    }
//                })
//                .showListener(new DialogInterface.OnShowListener() {
//                    @Override
//                    public void onShow(DialogInterface dialogInterface) {
//                        final MaterialDialog dialog = (MaterialDialog) dialogInterface;
//                        startThread(new Runnable() {
//                            @Override
//                            public void run() {
//                                while (dialog.getCurrentProgress() != dialog.getMaxProgress() &&
//                                        !Thread.currentThread().isInterrupted()) {
//                                    if (dialog.isCancelled())
//                                        break;
//                                    try {
//                                        Thread.sleep(50);
//                                    } catch (InterruptedException e) {
//                                        break;
//                                    }
//                                    dialog.incrementProgress(1);
//                                }
//                                ((Activity)context).runOnUiThread(new Runnable() {
//                                    @Override
//                                    public void run() {
//                                        mThread = null;
//                                        dialog.setContent("下载完成");
//                                    }
//                                });
//
//                            }
//                        });
//                    }
//                }).show();
    }


    /**
     * 下载安装包
     *
     * @param strPath
     */
    private void downloadTheFile(final String strPath) {
        fileEx = strURL.substring(strURL.lastIndexOf(".") + 1, strURL.length())
                .toLowerCase();
        fileNa = strURL.substring(strURL.lastIndexOf("/") + 1,
                strURL.lastIndexOf("."));
        try {
            if (strPath.equals(currentFilePath)) {
                doDownloadTheFile(strPath);
            }
            currentFilePath = strPath;
            Log.d(TAG + ">当前文件夹>>" + currentFilePath);
            Runnable r = new Runnable() {
                public void run() {
                    try {
                        doDownloadTheFile(strPath);
                    } catch (Exception e) {
                        Log.e(TAG + e.getMessage(), e);
                    }
                }
            };
            new Thread(r).start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 将安装包存储到本地
     */
    int fileSize;
    int downLoadFileSize;
    int downLoadCount;
    File myTempFile;

//    JSONArray array;

    private void doDownloadTheFile(String strPath) throws Exception {
        Log.d(TAG + ">getDataSource()");
        if (!URLUtil.isNetworkUrl(strPath)) {
            Log.d(TAG + ">getDataSource() It's a wrong URL!");
        } else {
            URL myURL = new URL(strPath);
            URLConnection conn = myURL.openConnection();
            conn.connect();
            InputStream is = conn.getInputStream();
            File currentTempFilePath = new File(
                    Environment.getExternalStorageDirectory() + "/"
                            + "miner" + "/resources");
            if (!currentTempFilePath.exists()) {
                currentTempFilePath.mkdirs();
            }
            File myTempFile = new File(
                    Environment.getExternalStorageDirectory() + "/"
                            + "miner" + "/resources/" + fileNa
                            + "." + fileEx);
            if (myTempFile.exists()) {
                myTempFile.delete();
            }
            downLoadFileSize = 0;
            downLoadCount = 0;
            dialog.setMax(100);
            int dhi = -dialog.getProgress();
            dialog.incrementProgressBy(-dialog.getProgress());
            fileSize = conn.getContentLength();
            if (is == null) {
                throw new RuntimeException("stream is null");
            }

            FileOutputStream fos = new FileOutputStream(myTempFile);
            byte buf[] = new byte[4096];
            do {
                int numread = is.read(buf);
                if (numread <= 0) {
                    break;
                }
                fos.write(buf, 0, numread);
                downLoadFileSize += numread;
                int result = downLoadFileSize * 100 / fileSize;
                // dialog.setProgress(result);
                if (downLoadCount == 0 || result - downLoadCount >= 16
                        || result == 100) {
                    downLoadCount += 1;
                    // handler.sendEmptyMessage(1);
                    dialog.setProgress(result);
                }
                if (result == 100) {
                    // handler.sendEmptyMessage(2);
                }

                // if(!diaLogger.isShowing()){
                // handler.sendEmptyMessage(1);
                // }
            } while (true);
            Log.d(TAG + ">getDataSource() Download  ok...");
            // dialog.cancel();
            //强制更新就不能消失
            if( app.updateMust!=1) {
                dialog.dismiss();
            }
            openFile(myTempFile);
            try {
                is.close();
                fos.close();
            } catch (Exception ex) {
                Log.e(TAG + ">getDataSource() error: " + ex.getMessage(), ex);
            }
        }
    }

//    Handler handler = new Handler() {

//        @Override
//        public void handleMessage(Message msg) {
//            switch (msg.what) {
//                case 1:
//                    // if (!diaLogger.isShowing()) {
//                    int result = downLoadFileSize * 100 / fileSize;
//                    mNotification.contentView = new RemoteViews(
//                            context.getPackageName(),
//                            R.layout.notification_progress_bar);// 通知栏中进度布局
//                    mNotification.contentView.setTextViewText(R.id.progress_detail,
//                            result + "%");
//                    mNotification.contentView.setProgressBar(R.id.progress_bar,
//                            100, result, true);
//                    nm.notify(0, mNotification);
//                case 2:
//                    int result2 = downLoadFileSize * 100 / fileSize;
//                    mNotification.contentView = new RemoteViews(
//                            context.getPackageName(),
//                            R.layout.notification_progress_bar);// 通知栏中进度布局
//                    mNotification.contentView.setTextViewText(R.id.progress_detail,
//                            "下载完成");
//                    mNotification.contentView.setProgressBar(R.id.progress_bar,
//                            100, result2, true);
//                    nm.notify(0, mNotification);
//                    // }
//                    // notify.contentView.setTextViewText(R.id.progressDetail,
//                    // result+"");
//                    // notify.contentView.setProgressBar(R.id.progressBar, 100,
//                    // result, false);
//                    // dialog.setProgress(result);
//                    break;
//
//                default:
//                    break;
//            }
//            super.handleMessage(msg);
//        }
//
//    };

    /**
     * 打开安装包
     *
     * @param f
     */
    private void openFile(File f) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        String type = getMIMEType(f);
        intent.setDataAndType(Uri.fromFile(f), type);
        context.startActivity(intent);
    }

    /**
     * 得到安装包的MIME类型
     *
     * @param f
     * @return
     */
    private String getMIMEType(File f) {
        String type = "";
        String fName = f.getName();
        String end = fName
                .substring(fName.lastIndexOf(".") + 1, fName.length())
                .toLowerCase();
        if (end.equals("m4a") || end.equals("mp3") || end.equals("mid")
                || end.equals("xmf") || end.equals("ogg") || end.equals("wav")) {
            type = "audio";
        } else if (end.equals("3gp") || end.equals("mp4")) {
            type = "video";
        } else if (end.equals("jpg") || end.equals("gif") || end.equals("png")
                || end.equals("jpeg") || end.equals("bmp")) {
            type = "image";
        } else if (end.equals("apk")) {
            type = "application/vnd.android.package-archive";
        } else {
            type = "*";
        }
        if (end.equals("apk")) {
        } else {
            type += "/*";
        }
        return type;
    }

    public void check() {
//        CheckUpdateTask task = new CheckUpdateTask(context);

        Log.d(TAG + ">更新URL:" + UrlConst.UPDATE_URL);
        //如果没有节点,则不更新
        if (LocalMark.SERVER_URL.getName().equals("")) {
            return;
        }
        String node_url = Arad.preferences.getString(LocalMark.SERVER_URL.getName(), "");
        node_url = node_url.replaceAll("http://", "");
        Log.d("node_url>>>>>>>>>" + node_url);
        if (node_url.lastIndexOf("/") > 0) {
            node_url = node_url.substring(0, node_url.lastIndexOf("/"));
        }

        Log.d(TAG + ">node_url: 节点>>:" + node_url);

//        task.execute(UrlConst.UPDATE_URL, node_url, Const.UPDATE_NICKNAME, versionName);


        AsyncTaskUtil task = new AsyncTaskUtil(new AsyncCallback() {

            @Override
            public String doInBackground(Object... params) {
                Post post = new Post((String) params[0]);
                if (params[1] == null || params[1].equals("")) {

                } else {
                    post = new Post((String) params[0]);
                    post.addParam("node_url", params[1]);
                    post.addParam("type", params[2]);
                    post.addParam("version", params[3]);
                    String str = post.getResultString();
                    Log.d("自动更新请求参数>>>node_url:" + params[1] + "| type:" + params[2] + "| version:" + params[3]);
                    Log.d("自动更新返回结果>>:" + str);
                }

                String result = post.getResultString();
                return result;
            }

            @Override
            public void ProgressUpdate(Integer... values) {
                // TODO Auto-generated method stub

            }

            @Override
            public void PreExecute() {
                // TODO Auto-generated method stub

            }

            @Override
            public void Cancelled() {

            }

            @Override
            public void Cancelled(String result) {

            }

            @Override
            public void PostExecute(String result) {
                Log.d(TAG + ">更新结果:" + result);
                JSONObject obj = JsonUtil.parseObject(result);
                try {
                    //获取是否更新状态 1需要更新 0 不需要更新
                    final int status = obj.getInt("status");
                    //更新出错
                    if (status == 0) {
                        if (!isAutoUpdate) {
                            if (obj.has("reason")) {
                                MessageUtils.showImageShortToast(context, obj.getString("reason"));
                            } else if (obj.has("info")) {
                                MessageUtils.showImageShortToast(context, obj.getString("info"));
                            }

                        }
                        return;
                    }
                    //状态信息
                    String info = obj.getString("info");


                    //需要更新
                    if (status == 1) {
                        JSONObject dataObj = obj.getJSONObject("data");
                        final int must = dataObj.getInt("must");
                        //是否必须更新 1 必须更新 0 不必须
                        app.updateMust = must;
                        //下载地址
                        JSONArray urlArray = dataObj.getJSONArray("download_url");
                        JSONObject urlObj = urlArray.getJSONObject(0);
                        download_url = urlObj.getString("url");
                        strURL = download_url;
                        //更新信息
                        update_info = dataObj.getString("update_info");
                        //更新需要的 md5校验
                        md5 = dataObj.getString("md5");
                        //是否有新版本
                        app.hasNewVersion = true;
                        //更新对话框
                        showResultDialog();
                    } else {
                        app.hasNewVersion = false;
                        //点击设置的更新
                        if (!isAutoUpdate) {
                            MessageUtils.showShortToast(context, "当前已是最新版本");
                        }
                    }

                } catch (Exception e) {
                    Log.e(e.getMessage());
                    MessageUtils.showImageShortToast(context, "更新异常");
                }

            }
        });
        task.execute(UrlConst.UPDATE_URL, node_url, Const.UPDATE_NICKNAME, versionName);


    }


    //结果提示框
    public void showResultDialog() {

        app.hasNewVersion = true;
        if (app.updateMust == 1) {
            new MaterialDialog.Builder(context).backgroundColorRes(R.color.white)
                    .title("版本更新").titleColorRes(R.color.color_tv333)
                    .content(update_info).contentColorRes(R.color.color_tv333)
                    .positiveText("立即更新").positiveColorRes(R.color.colorAccent)
                    .onAny(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
//                            showToast(which.name() + "!");

                            downloadTheFile(strURL);
//                    notificationInit();
                            showWaitDialog();
//                            dialog.show();

                        }
                    }).keyListener(new DialogInterface.OnKeyListener() {
                @Override
                public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                    if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                        dialog.dismiss();
                        System.exit(0);
                        return true;
                    }
                    return false;
                }
            }).cancelable(false).show();
        } else {

            new MaterialDialog.Builder(context).backgroundColorRes(R.color.white)
                    .title("版本更新").titleColorRes(R.color.color_tv333)
                    .content(update_info).contentColorRes(R.color.color_tv333)
                    .positiveText("立即更新").positiveColorRes(R.color.colorAccent)
                    .negativeText("下次再说").negativeColorRes(R.color.color_666)
                    .onAny(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
//                            showToast(which.name() + "!");
                            if (which.name().equals("POSITIVE")) {
                                downloadTheFile(strURL);
//                    notificationInit();
                                showWaitDialog();
                            } else {
                                dialog.dismiss();
                            }
                        }
                    }).show();


        }
    }
}
